package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/announcement")
public class AnnouncementServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("list".equals(action)) {
            listAnnouncements(request, response);
        } else if ("edit".equals(action)) {
            editAnnouncement(request, response);
        } else if ("delete".equals(action)) {
            deleteAnnouncement(request, response);
        } else {
            // 默认显示公告列表
            listAnnouncements(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("create".equals(action)) {
            createAnnouncement(request, response);
        } else if ("update".equals(action)) {
            updateAnnouncement(request, response);
        } else {
            response.sendRedirect("announcement?action=list");
        }
    }
    
    private void listAnnouncements(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM announcements ORDER BY create_time DESC";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            
            List<Map<String, Object>> announcements = new ArrayList<>();
            while (rs.next()) {
                Map<String, Object> announcement = new HashMap<>();
                announcement.put("id", rs.getInt("id"));
                announcement.put("title", rs.getString("title"));
                announcement.put("content", rs.getString("content"));
                announcement.put("author", rs.getString("author"));
                announcement.put("status", rs.getString("status"));
                announcement.put("createTime", rs.getTimestamp("create_time"));
                announcement.put("views", rs.getInt("views"));
                announcements.add(announcement);
            }
            
            request.setAttribute("announcements", announcements);
            request.getRequestDispatcher("admin-announcement.jsp").forward(request, response);
            
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "获取公告列表失败: " + e.getMessage());
            request.getRequestDispatcher("admin-announcement.jsp").forward(request, response);
        }
    }
    
    private void createAnnouncement(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String status = request.getParameter("status");
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "INSERT INTO announcements (title, content, status) VALUES (?, ?, ?)";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, title);
            stmt.setString(2, content);
            stmt.setString(3, status);
            
            int result = stmt.executeUpdate();
            if (result > 0) {
                request.setAttribute("success", "公告发布成功！");
            } else {
                request.setAttribute("error", "公告发布失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "公告发布失败: " + e.getMessage());
        }
        
        response.sendRedirect("announcement?action=list");
    }
    
    private void updateAnnouncement(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String status = request.getParameter("status");
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "UPDATE announcements SET title = ?, content = ?, status = ? WHERE id = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, title);
            stmt.setString(2, content);
            stmt.setString(3, status);
            stmt.setString(4, id);
            
            int result = stmt.executeUpdate();
            if (result > 0) {
                request.setAttribute("success", "公告更新成功！");
            } else {
                request.setAttribute("error", "公告更新失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "公告更新失败: " + e.getMessage());
        }
        
        response.sendRedirect("announcement?action=list");
    }
    
    private void deleteAnnouncement(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String id = request.getParameter("id");
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "DELETE FROM announcements WHERE id = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, id);
            
            int result = stmt.executeUpdate();
            if (result > 0) {
                request.setAttribute("success", "公告删除成功！");
            } else {
                request.setAttribute("error", "公告删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "公告删除失败: " + e.getMessage());
        }
        
        response.sendRedirect("announcement?action=list");
    }
    
    private void editAnnouncement(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String id = request.getParameter("id");
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM announcements WHERE id = ?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery();
            
            if (rs.next()) {
                Map<String, Object> announcement = new HashMap<>();
                announcement.put("id", rs.getInt("id"));
                announcement.put("title", rs.getString("title"));
                announcement.put("content", rs.getString("content"));
                announcement.put("status", rs.getString("status"));
                request.setAttribute("announcement", announcement);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "获取公告信息失败: " + e.getMessage());
        }
        
        request.getRequestDispatcher("admin-announcement-edit.jsp").forward(request, response);
    }
} 